import axios from 'axios';
import router from '@/router'
import { getToken } from '@/utils/auth'
import store from '@/store'
// http 状态码
const httpCodeMessage = {
  200: '请求成功',
  201: '修改数据成功',
  204: '删除数据成功',
  400: '请求格式有误',
  401: 'token无效',
  403: '权限不足',
  404: '请求不存在',
  410: '资源已删除',
  422: '验证错误',
  500: '服务器错误',
  502: '网关错误',
  503: '维护中',
  504: '连接超时',
};


const instance = axios.create({
  timeout: 10000,
  responseType: 'json',
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  },
});

instance.interceptors.request.use(
  config => {
    const { needAuth } = config;
    needAuth && (config.headers['Authorization'] = 'Bearer ' + getToken())
    return config
  },
  err => Promise.reject(err)
);

instance.interceptors.response.use(
  response => {
    if (!response || !response.data) {
      let msg = '请求错误.';
      return Promise.reject(new Error(msg));
    }
    const { data } = response;
    if (data.code === 0) return data.data;
    console.error(data.message)
    return Promise.reject(data);
  },
  err => {
    if (err && err.response) {
      const { status, data } = err.response;
      const errorMessage = (data && (data.message || data.error)) || httpCodeMessage[status];
      console.error(errorMessage);
      if (status === 401) {
        store.dispatch('logout')
      }
      return Promise.reject({
        message: errorMessage,
      });
    }
  }
);
let Request = function () { };
Request.install = function (Vue) {
  Vue.prototype.$request = instance;
  window.$request = instance;
};
export default Request;
